package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"net/http"
	"path"
	"strconv"
	"time"
	config2 "youku/api/basic/config"
	"youku/api/pkg"
	req2 "youku/api/req"
	"youku/youku-srv/basic/config"
	__ "youku/youku-srv/basic/proto"
)

func Send(ctx *gin.Context) {
	var req req2.SendReq
	ctx.ShouldBind(&req)
	code := rand.Intn(900000) + 100000
	if config.Rdb == nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "Redis 客户端未初始化",
			"data":    nil,
		})
		return
	}
	sms, err := pkg.Send(req.Phone, strconv.Itoa(code))
	if err != nil {
		return
	}
	conunt, _ := config.Rdb.Get(config.Ctx, req.Phone+"次数").Int()
	if conunt >= 3 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "五分钟内超过三次发送验证码",
			"data":    nil,
		})
	} else {
		if *sms.Body.Code != "OK" {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": *sms.Body.Message,
				"data":    nil,
			})
		} else {
			if conunt == 0 {
				config.Rdb.Set(config.Ctx, req.Phone+"次数", 1, time.Minute*5)
			} else {
				config.Rdb.Incr(config.Ctx, req.Phone+"次数")
			}
			ctx.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "发送成功",
				"data":    nil,
			})
			config.Rdb.Set(config.Ctx, req.Phone, code, 0)
		}

	}

}
func Upload(ctx *gin.Context) {
	var req req2.UploadReq
	ctx.ShouldBind(&req)
	file, m, err := ctx.Request.FormFile("image")
	if err != nil {
		return
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		return
	}
	ext := path.Ext(m.Filename)
	if ext != ".mp4" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "上传失败,格式不正确",
			"data":    nil,
		})
	} else {
		if m.Size >= 1024*1024*1024 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    500,
				"message": "上传失败,内存占用大于1gb",
				"data":    nil,
			})
		} else {
			if pkg.Baidu(upload) {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    200,
					"message": "审核通过,上传成功",
					"data":    upload,
				})
			} else {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    500,
					"message": "审核失败,上传失败",
					"data":    nil,
				})
			}

		}
	}

}
func VideoAdd(ctx *gin.Context) {
	var req req2.VideoAddReq
	ctx.ShouldBind(&req)
	r, err := config2.YouKu.VideoAdd(ctx, &__.VideoAddReq{
		Title:        req.Title,
		Desc:         req.Desc,
		CoverUrl:     req.CoverUrl,
		Status:       req.Status,
		Types:        req.Types,
		Channel:      req.Channel,
		PlayCount:    req.PlayCount,
		LikeCount:    req.LikeCount,
		CommentCount: req.CommentCount,
		CollectCount: req.CollectCount,
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "添加成功",
		"data":    r.VideoId,
	})
}
